package com.css.zfzx.sjcj.modules.hddcISCatalog.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.constants.PlatformConstants;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.PlatformDateUtils;
import com.css.bpm.platform.utils.PlatformObjectUtils;
import com.css.bpm.platform.utils.PlatformPageUtils;
import com.css.bpm.platform.utils.PlatformSessionUtils;
import com.css.bpm.platform.utils.UUIDGenerator;
import com.css.zfzx.sjcj.common.excel.handler.ActiveFaultVerifyBaseHandler;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.hddcISCatalog.repository.HddcIscatalogNativeRepository;
import com.css.zfzx.sjcj.modules.hddcISCatalog.repository.HddcIscatalogRepository;
import com.css.zfzx.sjcj.modules.hddcISCatalog.repository.entity.HddcIscatalogEntity;
import com.css.zfzx.sjcj.modules.hddcISCatalog.service.HddcIscatalogService;
import com.css.zfzx.sjcj.modules.hddcISCatalog.viewobjects.HddcIscatalogPageVO;
import com.css.zfzx.sjcj.modules.hddcISCatalog.viewobjects.HddcIscatalogQueryParams;
import com.css.zfzx.sjcj.modules.hddcISCatalog.viewobjects.HddcIscatalogVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author zyb
 * @date 2020-11-28
 */
@Service
public class HddcIscatalogServiceImpl implements HddcIscatalogService {

    private final HddcIscatalogRepository hddcIscatalogRepository;
    private final HddcIscatalogNativeRepository hddcIscatalogNativeRepository;
    private final ActiveFaultVerifyBaseHandler activeFaultVerifyBaseHandler;

    @Autowired
    public HddcIscatalogServiceImpl(HddcIscatalogRepository hddcIscatalogRepository,
                                    HddcIscatalogNativeRepository hddcIscatalogNativeRepository,
                                    ActiveFaultVerifyBaseHandler activeFaultVerifyBaseHandler) {
        this.hddcIscatalogRepository = hddcIscatalogRepository;
        this.hddcIscatalogNativeRepository = hddcIscatalogNativeRepository;
        this.activeFaultVerifyBaseHandler = activeFaultVerifyBaseHandler;
    }

    @Override
    public JSONObject queryHddcIscatalogs(HddcIscatalogQueryParams queryParams, int curPage, int pageSize,String sort,String order) {
        Page<HddcIscatalogPageVO> hddcIscatalogPage = this.hddcIscatalogNativeRepository.queryHddcIscatalogs(queryParams, curPage, pageSize, sort, order);
        return PlatformPageUtils.formatPageData(hddcIscatalogPage);
    }


    @Override
    public HddcIscatalogEntity getHddcIscatalog(String id) {
        return this.hddcIscatalogRepository.findById(id).orElse(null);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcIscatalogEntity saveHddcIscatalog(HddcIscatalogEntity hddcIscatalog) {
        String uuid = UUIDGenerator.getUUID();
        hddcIscatalog.setUuid(uuid);
        hddcIscatalog.setCreateUser(PlatformSessionUtils.getUserId());
        Timestamp now = PlatformDateUtils.getCurrentTimestamp();
        hddcIscatalog.setCreateTime(now);
        hddcIscatalog.setUpdateTime(now);
        hddcIscatalog.setIsValid(PlatformConstants.Y);
        hddcIscatalog.setQualityinspectionStatus(PlatformConstants.N);
        hddcIscatalog.setExtends10(PlatformConstants.Y);
        this.hddcIscatalogRepository.save(hddcIscatalog);
        return hddcIscatalog;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcIscatalogEntity updateHddcIscatalog(HddcIscatalogEntity hddcIscatalog) {
        HddcIscatalogEntity entity = hddcIscatalogRepository.findById(hddcIscatalog.getUuid()).get();
        UpdateUtil.copyNullProperties(entity,hddcIscatalog);
        hddcIscatalog.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcIscatalog.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcIscatalogRepository.save(hddcIscatalog);
        return hddcIscatalog;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcIscatalogs(List<String> ids) {
        List<HddcIscatalogEntity> hddcIscatalogList = this.hddcIscatalogRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(hddcIscatalogList) && hddcIscatalogList.size() > 0) {
            for(HddcIscatalogEntity hddcIscatalog : hddcIscatalogList) {
                hddcIscatalog.setIsValid("0");
                hddcIscatalog.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcIscatalog.setUpdateTime(new Date());
                this.hddcIscatalogRepository.save(hddcIscatalog);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        return PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
    }

    @Override
    public void exportFile(HddcIscatalogQueryParams queryParams, HttpServletResponse response) {
        List<HddcIscatalogEntity> yhDisasterEntities = hddcIscatalogNativeRepository.exportYhDisasters(queryParams);
        List<HddcIscatalogVO> list=new ArrayList<>();
        for (HddcIscatalogEntity entity:yhDisasterEntities) {
            HddcIscatalogVO yhDisasterVO=new HddcIscatalogVO();
            BeanUtils.copyProperties(entity,yhDisasterVO);
            list.add(yhDisasterVO);
        }
        EasyPoiExcelUtil.exportExcel(list, "1970年以来地震目录-点", "1970年以来地震目录-点", HddcIscatalogVO.class, "1970年以来地震目录-点.xls", response);
    }

    @Override
    public String exportExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            params.setVerifyHandler(activeFaultVerifyBaseHandler);
            // 获取到Excel数据
            ExcelImportResult<HddcIscatalogVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcIscatalogVO.class, params);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                for (HddcIscatalogVO yhDisasterVO : result.getFailList()) {
                    returnMsg.append("第").append(yhDisasterVO.getRowNum()).append("行").append(yhDisasterVO.getErrorMsg()).append("<br/>");
                }
                if (returnMsg.length() > 0)
                    return returnMsg.toString();
            }
            List<HddcIscatalogVO> list = result.getList();
            //保存
            saveDisasterList(list);
            return returnMsg.append("成功导入").append(result.getList().size()).append("条记录").toString();
        } catch (Exception e) {
            return "导入失败，请检查数据正确性";
        }
    }
    /**
     * 批量存入库表并且返回错误数量
     *
     */
    public void saveDisasterList( List<HddcIscatalogVO> list) {
        for (HddcIscatalogVO hddcIscatalogVO : list) {
            HddcIscatalogEntity yhDisasterEntity = new HddcIscatalogEntity();
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(hddcIscatalogVO, yhDisasterEntity);
            saveHddcIscatalog(yhDisasterEntity);
        }
    }
    @Override
    public void deleteByProjectId(List<String> projectIds) {
        List<HddcIscatalogEntity> hddcIscatalogList = this.hddcIscatalogRepository.queryHddcIscatalogsByProjectId(projectIds);
        if(!PlatformObjectUtils.isEmpty(hddcIscatalogList) && hddcIscatalogList.size() > 0) {
            for(HddcIscatalogEntity hddcIscatalog : hddcIscatalogList) {
                hddcIscatalog.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcIscatalog.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcIscatalog.setIsValid(PlatformConstants.N);
                this.hddcIscatalogRepository.save(hddcIscatalog);
            }
        }
    }

    @Override
    public void deleteByTaskId(List<String> taskIds) {
        List<HddcIscatalogEntity> hddcIscatalogList = this.hddcIscatalogRepository.queryHddcIscatalogsByTaskId(taskIds);
        if(!PlatformObjectUtils.isEmpty(hddcIscatalogList) && hddcIscatalogList.size() > 0) {
            for(HddcIscatalogEntity hddcIscatalog : hddcIscatalogList) {
                hddcIscatalog.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcIscatalog.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcIscatalog.setIsValid(PlatformConstants.N);
                this.hddcIscatalogRepository.save(hddcIscatalog);
            }
        }
    }

}
